//
//  ViewController.m
//  19-JSON
//
//  Created by 王道林 on 16/8/9.
//  Copyright © 2016年 王道林. All rights reserved.
//

#import "ViewController.h"
#import "CustomLayout.h"
#import "ContentTitle.h"
#import "TitleCollectionViewCell.h"

@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, CustomLayoutDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray<ContentTitle *> *contentArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self createData];
    
    CustomLayout *layout = (CustomLayout *)self.collectionView.collectionViewLayout;
    layout.delegate = self;
    
    
    // 代码创建collectionview
    
}

- (void)createData
{
    self.contentArray = [NSMutableArray array];
    // JSON解析
    // 通过一个Data, 将JSON格式转化成oc认识的内容
    // 数组/字典
    // 获取JSON的data
    NSString *datapath = [[NSBundle mainBundle] pathForResource:@"FistJSON" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:datapath];
    
    //NSJSONSerialization
    NSError *error = nil;
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    NSLog(@"%@",jsonDic);
    
    NSArray *list = jsonDic[@"tabs"][@"list"];

    for (NSDictionary *dic in list) {
        ContentTitle *content = [ContentTitle contentTitleWithDictionary:dic];
        [_contentArray addObject:content];
    }
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _contentArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"wang" forIndexPath:indexPath];
    cell.contectTitle = _contentArray[indexPath.row];
    return cell;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout heightForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *string = _contentArray[indexPath.row].title;
    
   CGRect rect = [string boundingRectWithSize:CGSizeMake(0, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
    CGFloat width = ceilf(CGRectGetWidth(rect));
    return width;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
